import './assets/css/main.less'
var count = 60
var successTime = 0
var timer = null
var inputValue = []
const req = require.context('./assets/img', true, /(\.jpg|\.png)$/);
const requireAll = requireContext => requireContext.keys().map(requireContext)
const imgDatas = requireAll(req)
const ycy = []
const not_ycy = []
imgDatas.forEach(i => {
    (/not_ycy/.test(i) ? not_ycy : ycy).push(i)
})
console.log(ycy, not_ycy)

// 预加载图片
const load = ( src ) => {
	return new Promise( ( resolve, reject ) => {
		const img = new Image();
		img.src = src;
		img.onload = () => resolve( src );
		img.onerror = ( e ) => reject( e );

	} );
};

const promises = []
imgDatas.forEach(i => {
    promises.push(load(i)) 
})

// 程序入口
Promise.all(promises).then(()=>{
    $('mask').style.display = 'none'
    $('wrap').style.display = 'block'
    // mp3
    const audioNode = document.createElement('audio')
    audioNode.src = 'http://118.24.14.113:8888/kll.mp3'
    audioNode.setAttribute('autoplay', true)
    audioNode.setAttribute('controls', true)
    audioNode.setAttribute('loop', true)
    $('wrap').appendChild(audioNode)
    init()
})


function $(id) {
    return document.getElementById(id)
}
function init() {
    $('button').addEventListener('click', changeImg, false)
    changeImg(1)
}

// flag: 1 初始化 ; 2check函数执行后刷新图片 ; 若为event对象表示点击了开始按钮
function changeImg(flag) {
    if (timer && flag !== 2) {
        return
    }
    var isClikType = typeof flag !== 'number'
    // 开始游戏
    if (isClikType) {
        successTime = 0
        inputValue = []
        count = 60
        $('successTime').innerHTML = `得分${successTime}`
        $('inputValue').innerHTML = `当前输入值:${inputValue}`
        $('timer').innerHTML = `倒计时${count}`
        startGame()
    }

    var arr = [].slice.call(document.getElementsByTagName('img'))
    arr.forEach(i => {
        i.src = flag === 1 ? ycy[0] : setSrc()
    })
}

function startGame(params) {
    startTimer()
}

function startTimer(params) {
    setKeydownEvent()
    if (timer) return
    timer = setInterval(() => {
        if (!count) {
            removeKeydownEvent()
            timer = clearInterval(timer) || null
            alert(`${successTime}次`)
            $('timer').innerHTML = `倒计时${count}`
            return
        }
        count--
        $('timer').innerHTML = `倒计时${count}`
    }, 1000);
}

function setSrc(params) {
    return Math.random() > 0.5 ? randomNum(not_ycy) : randomNum(ycy)
}

function randomNum(arr) {
    return arr[Math.floor(Math.random() * arr.length)]
}

// 删除监听键盘事件
function removeKeydownEvent() {
    document.removeEventListener('keydown', keyDownHandler, false)
}
// 监听键盘事件
function setKeydownEvent() {
    document.addEventListener('keydown', keyDownHandler, false)

}

function keyDownHandler(ev) {
    var vailidKeyCodeObj = {
        32: 32,
        97: 1,
        98: 2,
        99: 3,
        100: 4,
        101: 5,
        102: 6,
        103: 7,
        104: 8,
        105: 9
    }
    var ev = ev || window.event;
    if (
        vailidKeyCodeObj[ev.keyCode]
    ) {
        inputNumber(vailidKeyCodeObj[ev.keyCode])
    }
}

function inputNumber(num) {
    if (num === 32) {
        check()
    } else {
        inputValue.push(num)
        $('inputValue').innerHTML = `当前输入值:${inputValue.join()}`
    }
}

function check() {
    const parentNodes = document.getElementsByClassName('img')
    // 先过滤，再返回id，排序，转为字符串
    const trueResult = [].slice.call(parentNodes).filter(i => !/not_ycy/.test(i.innerHTML)).map(data => data.firstElementChild.id).sort((a, b) => a - b).join()
    if (inputValue.join() === trueResult) {
        successTime += 1
        $('successTime').innerHTML = `得分${successTime}`
    }
    inputValue = []
    $('inputValue').innerHTML = `当前输入值:`
    changeImg(2)
}